package com.merchant.map;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.Window;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnCameraChangeListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.LocationSource.OnLocationChangedListener;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeRoad;
import com.amap.api.services.geocoder.StreetNumber;
import com.merchant.constant.Constants;
import com.zjxfood.merchant.activity.R;

public class LocationActivity extends Activity implements OnClickListener {
	private AMap aMap;
	private MapView mapView;
	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager;
	private TextView textViewLocationInfo;
	private Marker locationMarker;
	private LinearLayout layoutLoading;
	private LatLng locationLatLng;
	public static Drawable mapPrintScreen;
	private Handler handler = new Handler();
	private ImageView map_title_back_image;
	private TextView map_modify;
	public static String ACTION_MAPP = "XX";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loction);
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState); //此处必须加上
		init();
	}

	private void init() {
		layoutLoading = (LinearLayout) findViewById(R.id.layout_loading);
//		findViewById(R.id.btn_back).setOnClickListener(clickListener);
		map_modify = (TextView) findViewById(R.id.map_modify);
		map_title_back_image = (ImageView) findViewById(R.id.map_title_back_image);
		map_modify.setOnClickListener(this);
		map_title_back_image.setOnClickListener(this);
		if (aMap == null) {
			aMap = mapView.getMap();
			if (AMapUtil.checkReady(this, aMap)) {
				setUpMap();
			}
		}
	}

	private void setUpMap() {
		aMap.setOnCameraChangeListener(cameraChangeListener);
		aMap.setInfoWindowAdapter(infoWindowAdapter);
		mAMapLocationManager = LocationManagerProxy
				.getInstance(LocationActivity.this);
		aMap.setLocationSource(locationSource);
		aMap.setMyLocationEnabled(true);// 设置为true表示系统定位按钮显示并响应点击，false表示隐藏，默认是false
		aMap.getUiSettings().setMyLocationButtonEnabled(false);
		aMap.getUiSettings().setTiltGesturesEnabled(false);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.map_title_back_image:
			finish();
			break;
		case R.id.map_modify:
			Intent mIntent = new Intent(ACTION_MAPP);
			mIntent.putExtra("JD", Constants.getlat);
			// mIntent.putExtra("WD", Constants.geoLng);
			// 发送广播
			sendBroadcast(mIntent);
			finish();
			break;
		}
	}
	/**
	 * �?地图上添加marker
	 * 
	 * @param latLng
	 */
	private void addMarker(LatLng latLng, String desc) {
		MarkerOptions markerOptions = new MarkerOptions();
		markerOptions.position(latLng);
		markerOptions.title("[我的位置]");
		markerOptions.snippet(desc);
		markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
		locationMarker = aMap.addMarker(markerOptions);
	}

	View.OnClickListener clickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			
//			case R.id.btn_back:
//				finish();
//				break;
			}
		}
	};

	LocationSource locationSource = new LocationSource() {

		@Override
		public void deactivate() {
			mListener = null;
			if (mAMapLocationManager != null) {
				mAMapLocationManager.removeUpdates(aMapLocationListener);
				mAMapLocationManager.destroy();
			}
			mAMapLocationManager = null;
		}

		@Override
		public void activate(OnLocationChangedListener listener) {
			mListener = listener;
			if (mAMapLocationManager == null) {
				mAMapLocationManager = LocationManagerProxy
						.getInstance(LocationActivity.this);
			}
			/*
			 * mAMapLocManager.setGpsEnable(false);//
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true
			 */
			// Location API定位采用GPS和网络混合定位方式，时间�?短是5000毫秒
			mAMapLocationManager.requestLocationData(
					LocationProviderProxy.AMapNetwork, 5000, 10,
					aMapLocationListener);
		}
	};

	AMapLocationListener aMapLocationListener = new AMapLocationListener() {

		@Override
		public void onLocationChanged(AMapLocation aLocation) {
			if (mListener != null) {
				// 此处注释掉，表示不用系统提供的定位图标等
				// mListener.onLocationChanged(aLocation);
			}
			if (aLocation != null) {
				Double geoLat = aLocation.getLatitude();
				Double geoLng = aLocation.getLongitude();
				locationLatLng = new LatLng(geoLat, geoLng);
				Constants.getlat = geoLng + "," + geoLat;
				String desc = "";
				Bundle locBundle = aLocation.getExtras();
				if (locBundle != null) {
					desc = locBundle.getString("desc");
				}
				addMarker(locationLatLng, desc);
				locationMarker.showInfoWindow();// 显示信息窗口
				aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
						locationLatLng, 15));
				locationSource.deactivate();
				layoutLoading.setVisibility(View.GONE);
			}
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onLocationChanged(Location location) {
		}

	};

	OnCameraChangeListener cameraChangeListener = new OnCameraChangeListener() {

		@Override
		public void onCameraChangeFinish(CameraPosition position) {
			if (locationMarker != null) {

				final LatLng latLng = position.target;
				new Thread(new Runnable()
				{
					
					@Override
					public void run()
					{
						GeocodeSearch geocodeSearch = new GeocodeSearch(LocationActivity.this);
						LatLonPoint point =new LatLonPoint(latLng.latitude, latLng.longitude);
						RegeocodeQuery regeocodeQuery = new RegeocodeQuery(point, 1000,GeocodeSearch.AMAP);
						RegeocodeAddress address = null;
						try {
							address = geocodeSearch.getFromLocation(regeocodeQuery);
						} catch (AMapException e) {
							e.printStackTrace();
						}
						if(null==address){
							return;
						}
						StringBuffer stringBuffer = new StringBuffer();
						String area = address.getProvince();//省或直辖�?
						String loc = address.getCity();//地级市或直辖�?
						String subLoc = address.getDistrict();//区或县或县级�?
						String ts = address.getTownship();//乡镇
						String thf = null;//道路
						List<RegeocodeRoad> regeocodeRoads = address.getRoads();//道路列表
						if(regeocodeRoads != null && regeocodeRoads.size() > 0)
						{
							RegeocodeRoad regeocodeRoad = regeocodeRoads.get(0);
							if(regeocodeRoad != null)
							{
								thf = regeocodeRoad.getName();
							}
						}
						String subthf = null;//门牌�?
						StreetNumber streetNumber =	address.getStreetNumber();
						if(streetNumber != null)
						{
							subthf = streetNumber.getNumber();
						}
						String fn = address.getBuilding();//标志性建�?,当道路为null时显�?
						if (area != null)
							stringBuffer.append(area);
						if(loc!=null&&!area.equals(loc))
							stringBuffer.append(loc);
						if (subLoc != null)
							stringBuffer.append(subLoc);
						if (ts != null)
							stringBuffer.append(ts);
						if (thf != null)
							stringBuffer.append(thf);
						if (subthf != null)
							stringBuffer.append(subthf);
						if ((thf == null && subthf == null) && fn != null&&!subLoc.equals(fn))
							stringBuffer.append(fn + "附近");
						locationMarker.setSnippet(stringBuffer.toString());
						handler.post(new Runnable()
						{
							
							@Override
							public void run()
							{
								locationMarker.showInfoWindow();
							}
						});
					}
				}).start();

			
			}
		}

		@Override
		public void onCameraChange(CameraPosition position) {
			if (locationMarker != null) {
				LatLng latLng = position.target;
				locationMarker.setPosition(latLng);
			}
		}
	};

	InfoWindowAdapter infoWindowAdapter = new InfoWindowAdapter() {

		@Override
		public View getInfoWindow(Marker marker) {
			return null;
		}

		@Override
		public View getInfoContents(Marker marker) {
			View mContents = getLayoutInflater().inflate(R.layout.custom_info_contents,
					null);
			render(marker, mContents);
			return mContents;
		}
	};
	
	class GetLocationTask extends AsyncTask<Object, Integer, Object>{

		@Override
		protected Object doInBackground(Object... params) {
			return null;
		}
		
		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			
			
		}
		
	}

	/** 自定义infowindow的样�? */
	public void render(Marker marker, View view) {
		String title = marker.getTitle();
		TextView titleUi = ((TextView) view.findViewById(R.id.title));
		if (title != null) {
			titleUi.setText(title);
		} else {
			titleUi.setText("");
		}
		String snippet = marker.getSnippet();
		TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
		if (snippet != null) {
			snippetUi.setText(snippet);
		} else {
			snippetUi.setText("");
		}
	}

	/**
	 * marker点击时跳动一�?
	 */
	public void jumpPoint(final Marker marker, final LatLng latLng) {

		final Handler handler = new Handler();
		final long start = SystemClock.uptimeMillis();
		Projection proj = aMap.getProjection();
		Point startPoint = proj.toScreenLocation(latLng);
		startPoint.offset(0, -100);
		final LatLng startLatLng = proj.fromScreenLocation(startPoint);
		final long duration = 1500;

		final Interpolator interpolator = new BounceInterpolator();
		handler.post(new Runnable() {
			@Override
			public void run() {
				long elapsed = SystemClock.uptimeMillis() - start;
				float t = interpolator.getInterpolation((float) elapsed
						/ duration);
				double lng = t * latLng.longitude + (1 - t)
						* startLatLng.longitude;
				double lat = t * latLng.latitude + (1 - t)
						* startLatLng.latitude;
				marker.setPosition(new LatLng(lat, lng));
				if (t < 1.0) {
					handler.postDelayed(this, 16);
				}
			}
		});
	}

	/**
	 * 把一个view转化成bitmap对象
	 */
	public static Bitmap getViewBitmap(View view) {
		view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
				MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		return bitmap;
	}

	/**
	 * 把一个xml布局文件转化成view
	 */
	public View getView(String title, String text) {
		View view = getLayoutInflater().inflate(R.layout.marker, null);
		// TextView text_title = (TextView)  
		// view.findViewById(R.id.marker_title);
		textViewLocationInfo = (TextView) view.findViewById(R.id.marker_text);
		// text_title.setText(title);
		textViewLocationInfo.setText(text);
		return view;
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		locationSource.deactivate();
		mapView.onPause();
	}
	
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}
	
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		mapView.onDestroy();
	}

}
